<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/8/18
 * Time: 17:14
 */

namespace app\alliance\controller;


use app\service\IGeTuiService;
use app\service\ResourceService;
use Redis\Redis;
use think\Db;

class Chat extends Common
{
    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 好友列表(通讯录)
     */
    function friendsList()
    {
        # 查询标识
        $mark = input('post.mark');
        if ($mark == 'list' or empty($mark)) {
            # 查询好友列表 , 通讯录
            $status = 2;
            $_where = "member_code = '" . $this->code . "'";
            $field = 'thumb,if(note_name is null or note_name="",nickname,note_name) nickname,phone,friends_code,member_code';
        } else {
            # 查询好友申请列表 ==>apply
            $status = 1;
            $_where = "friends_code = '" . $this->code . "'";
            $field = "(select head_portrait from member where code = member_code) thumb,
            (select name from member where code = member_code) nickname,
            (select phone from member where code = member_code) phone,
            friends_code ,member_code ";
        }
        # ID/名称/手机号
        $searchInfo = input('post.searchInfo');
        if (!empty($searchInfo)) {
            $_where .= " and (friends_code = '" . $searchInfo . "' or phone like '%" . $searchInfo . "%' or nickname like '%" . $searchInfo . "%')";
        }
        $list = Db::table('friends')
            ->field($field . ',relation_ship,status,ditrict_info,apply_info')
            ->where(array('status' => $status))
            ->where($_where)
            ->select();
        if (empty($list)) {
            $list = groupByInitials($list, 'nickname');
        }
        return array('status' => true, 'msg' => '获取成功', 'list' => $list, 'countNum' => count($list));
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 添加好友
     */
    function addFriends()
    {
        # 好友ID
        $friends_code = strtoupper(trim(input('post.friends_code')));
        if (!empty($friends_code)) {
            # 判断对方是否是我的好友
            $friendsJudge = Db::table('friends')->where(array('member_code' => $this->code, 'friends_code' => $friends_code))
                ->where("status != 3 and status != 4")->find();
            # 申请说明
            $apply_info = input('post.apply_info');
            # 查询好友信息
            $friendsInfo = Db::table('member')->field('code,name,head_portrait,phone,address,p_code')->where(array('code' => $friends_code))->find();
            if (!empty($friendsInfo)) {
                # 判断好友关系
                if ($this->memberInfo['p_code'] == $friendsInfo['code']) {
                    # 我的推荐人
                    $ship = 1;
                } elseif ($friendsInfo['p_code'] = $this->code) {
                    # 我的直推
                    $ship = 2;
                } else {
                    # 判断是我的团队还是好友
                    $p_code = Db::table('member')->field('p_code')->where(array('p_code' => $friendsInfo['p_code']))->find()['p_code'];
                    if ($this->code == $p_code) {
                        # 我的团队
                        $ship = 3;
                    } else {
                        # 我的好友
                        $ship = 4;
                    }
                }
                if (empty($friendsJudge)) {
                    # 添加申请信息
                    Db::table('friends')->insert(array(
                        'member_code' => $this->code,
                        'friends_code' => $friends_code,
                        'thumb' => $friendsInfo['head_portrait'],
                        'nickname' => $friendsInfo['name'],
                        'relation_ship' => $ship,
                        'phone' => $friendsInfo['phone'],
                        'ditrict_info' => $friendsInfo['address'],
                        'apply_info' => $apply_info
                    ));
                    # 发送消息
                    $igetui = new IGeTuiService();
                    $igetui->pushMessageToSingle('好友申请', '好友申请', $this->memberInfo['name'] . '请求添加您为好友', $friends_code, 2);
                    return array('status' => true, 'msg' => '已发送添加好友申请');
                } else {
                    # 判断我是不是对方的好友
                    $friends = Db::table('friends')->where(array('member_code' => $friends_code, 'friends_code' => $this->code))
                        ->where("status != 3 and status != 4")->find();
                    if (empty($friends)) {
                        # 添加申请信息
                        Db::table('friends')->insert(array(
                            'member_code' => $this->code,
                            'friends_code' => $friends_code,
                            'thumb' => $friendsInfo['head_portrait'],
                            'nickname' => $friendsInfo['name'],
                            'relation_ship' => $ship,
                            'phone' => $friendsInfo['phone'],
                            'ditrict_info' => $friendsInfo['address'],
                            'apply_info' => $apply_info
                        ));
                        # 发送消息
                        $igetui = new IGeTuiService();
                        $igetui->pushMessageToSingle('好友申请', '好友申请', $this->memberInfo['name'] . '请求添加您为好友', $friends_code, 2);
                    }
                    return array('status' => false, 'msg' => '已发送添加好友申请');
                }
            } else {
                return array('status' => false, 'msg' => '好友信息不存在');
            }
        } else {
            return array('status' => false, 'msg' => '请选择你要添加的好友');
        }
    }

    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @content 好友审核(接受/拒绝)
     */
    function friendAudit()
    {
        $friends_code = strtoupper(trim(input('post.friends_code')));
        if (!empty($friends_code)) {
            # 接收审核结果
            $choice = input('post.choice');
            if ($choice == 1) {
                # 判断我是不是对方的好友
                $friends = Db::table('friends')->where(array('member_code' => $friends_code,
                    'friends_code' => $this->code, 'status' => 2))->find();
                if (empty($friends)) {
                    # 审核通过
                    Db::table('friends')->where(array('member_code' => $friends_code, 'friends_code' => $this->code, 'status' => 1))
                        ->update(array('status' => 2, 'apply_time' => date('Y-m-d H:i:s')));
                    $friendsInfo = Db::table('member')->field('code,name,head_portrait,phone,address,p_code')->where(array('code' => $friends_code))->find();
                    # 判断好友关系
                    if ($this->memberInfo['p_code'] == $friendsInfo['code']) {
                        # 我的推荐人
                        $ship = 1;
                    } elseif ($friendsInfo['p_code'] = $this->code) {
                        # 我的直推
                        $ship = 2;
                    } else {
                        # 判断是我的团队还是好友
                        $p_code = Db::table('member')->field('p_code')->where(array('p_code' => $friendsInfo['p_code']))->find()['p_code'];
                        if ($this->code == $p_code) {
                            # 我的团队
                            $ship = 3;
                        } else {
                            # 我的好友
                            $ship = 4;
                        }
                    }
                } else {
                    # 是对方的好友
                    Db::table('friends')->where(array('member_code' => $friends_code, 'friends_code' => $this->code, 'status' => 1))->delete();
                    Db::table('friends')->where(array('member_code' => $friends_code, 'friends_code' => $this->code, 'status' => 2))
                        ->update(array('apply_time' => date('Y-m-d H:i:s')));
                }
                # 判断对方是不是我的好友
                $friendsState = Db::table('friends')->where(array('member_code' => $this->code,
                    'friends_code' => $friends_code, 'status' => 2))->find();
                if (empty($friendsState)) {
                    Db::table('friends')->insert(array(
                        'member_code' => $this->code,
                        'friends_code' => $friends_code,
                        'thumb' => $friendsInfo['head_portrait'],
                        'nickname' => $friendsInfo['name'],
                        'status' => 2,
                        'relation_ship' => $ship,
                        'phone' => $friendsInfo['phone'],
                        'ditrict_info' => $friendsInfo['address']
                    ));
                }
            } else {
                # 拒绝添加
                Db::table('friends')->where(array('member_code' => $friends_code, 'friends_code' => $this->code, 'status' => 1))
                    ->update(array('status' => 3, 'apply_time' => date('Y-m-d H:i:s')));
            }
            return array('status' => true, 'msg' => '操作成功');
        } else {
            return array('status' => false, 'msg' => '请选择好友,进行操作');
        }
    }

    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @content 删除好友
     */
    function delFriends()
    {
        # 好友ID
        $friends_code = strtoupper(trim(input('post.friends_code')));
        if (!empty($friends_code)) {
            Db::table('friends')->where(array('member_code' => $this->code, 'friends_code' => $friends_code))->update(array('status' => 4));
            return array('status' => true, 'msg' => '操作成功');
        } else {
            return array('status' => false, 'msg' => '请选择好友,进行操作');
        }
    }

    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @content 修改备注
     */
    function modifyNoteName()
    {
        # 接收人
        $receiver = strtoupper(trim(input('post.receiver')));
        # 备注名
        $note_name = input('post.note_name');
        if (!empty($receiver)) {
            # 修改备注
            Db::table('friends')->where(array('member_code' => $this->code, 'friends_code' => $receiver, 'status' => 2))->update(array('note_name' => $note_name));
            if (!empty($note_name)) {
                if (empty(trim($note_name))) {
                    $note_name = Db::table('friends')->field('nickname')
                        ->where(array('member_code' => $this->code, 'friends_code' => $receiver, 'status' => 2))
                        ->find()['nickname'];
                }
                # 修改聊天记录的姓名
                # 查询这两个人的记录
                $log = Db::connect("db_config2")->table("chat")
                    ->where(array("main" => $this->code, "relevance" => $receiver))->find();
                if (!empty($log['content'])) {
                    $content = json_decode($log['content'], true);
                    $content['friendName'] = $note_name;
                    Db::connect("db_config2")->table("chat")
                        ->where(array("main" => $this->code, "relevance" => $receiver))
                        ->update(array("content" => json_encode($content, JSON_UNESCAPED_UNICODE), 'receipt_name' => $note_name));
                }
            }
            return array('status' => true, 'msg' => '修改成功');
        } else {
            return array('status' => false, 'msg' => '请补全信息');
        }
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 查询敏感词汇列表
     */
    function sensitiveWord()
    {
        $redis = new Redis();
        $info = $redis->hGetJson('sensitive', 'word');
        if (empty($info)) {
            $info = Db::table('sensitive_word')->field('words')->select();
            $redis->hSetJson('sensitive', 'word', $info);
        }
        return array('status' => true, 'msg' => '查询成功', 'info' => $info);
    }

    /**
     * @return array
     * @content 添加敏感词汇使用记录
     */
    function sensitiveWordUse()
    {
        # 敏感词汇 id
        $sensitive_id = input('post.id');
        if (!empty($sensitive_id) and is_array($sensitive_id)) {
            # 添加记录
            $_info = array();
            foreach ($sensitive_id as $v) {
                array_push($_info, array('sensitive_id' => $v, 'member_code' => $this->code, 'create_time' => date('Y-m-d H:i:s')));
            }
            if (!empty($_info)) {
                Db::table('log_sensitive_use')->insertAll($_info);
            }
            # 增加次数
            $sensitiveId = implode(',', $sensitive_id);
            Db::query("update sensitive_word set as_often=as_often+1,use_num=use_num+1 where id in (" . $sensitiveId . ")");
            return array('status' => true, 'msg' => '添加记录成功');
        } else {
            return array('status' => false, 'msg' => '使用的词汇为空');
        }
    }

    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 聊天记录存储
     */
    function chatLog()
    {
        # 发送人
        $_sender = $this->code;
        # 接收人
        $_receipter = strtoupper(trim(input("post.receiver")));
        # 发送内容
        $_content = input("post.content");
        if (!empty($_receipter) and !empty($_content)) {
            $redis = new Redis();
            # 查询是否存在
            $_main_inner = Db::connect("db_config2")->table("chat")
                ->where(array("main" => $_sender, "relevance" => $_receipter))->find();
            # 发送人信息
            $_send_name = $redis->hGetJson('memberInfo', $_sender);
            if (empty($_send_name))
                $_send_name = Db::table("member")->field("name,phone,code")->where(array("code" => $_sender))->find();
            # 接收人信息
            $_receipt_name = $redis->hGetJson('memberInfo', $_receipter);
            if (empty($_receipt_name))
                $_receipt_name = Db::table("member")->field("name,phone,code")->where(array("code" => $_receipter))->find();
            if (!empty($_main_inner)) {
                Db::connect("db_config2")->table("chat")
                    ->where(array("main" => $_sender, "relevance" => $_receipter))
                    ->update(array("content" => $_content,'time'=>time()));
            } else {
                $_send_array = array("main" => $_sender, "relevance" => $_receipter, "send_name" => $_send_name['name'],
                    "send_phone" => $_send_name['phone'], "send_code" => $_send_name['code'], "receipt_name" => $_receipt_name['name'],
                    "receipt_phone" => $_receipt_name['phone'], "receipt_code" => $_receipt_name['code'],
                    "content" => $_content,"time"=>time());
                Db::connect("db_config2")->table("chat")->insert($_send_array);
            }
//            $_receipt_inner = Db::connect("db_config2")->table("chat")
//                ->where(array("main" => $_receipter, "relevance" => $_sender))->find();
//            if (!empty($_receipt_inner)) {
//                Db::connect("db_config2")->table("chat")
//                    ->where(array("main" => $_receipter, "relevance" => $_sender))
//                    ->update(array("content" => $_content));
//            } else {
//                $_receipt_array = array("main" => $_receipter, "relevance" => $_sender,
//                    "send_name" => $_receipt_name['name'], "send_phone" => $_receipt_name['phone'], "send_code" => $_receipt_name['code'],
//                    "receipt_name" => $_send_name['name'], "receipt_phone" => $_send_name['phone'], "receipt_code" => $_send_name['code'],
//                    "content" => $_content);
//                Db::connect("db_config2")->table("chat")->insert($_receipt_array);
//            }
            # 活跃人数加一
            $this->chatActivity();
            # 发送消息
            $igetui = new IGeTuiService();
            $igetui->pushMessageToSingle('聊一聊', '聊一聊', $_send_name['name'] . '和您说话啦,前去查看', $_receipter, 2);
            return array('status' => true, 'msg' => '存储成功');
        } else {
            return array('status' => false, 'msg' => '发送内容/接收人为空');
        }
    }

    /**
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 增加当前时间段的活跃人数
     */
    function chatActivity()
    {
        # 当前小时
        $hour = intval(date('H'));
        $start = $hour - 1;
        $redis = new Redis();
        # 判断当前时间 是否添加过
        $currentTimeState = $redis->hGet('chatActivity', $this->code . '=>' . $hour);
        if (empty($currentTimeState)) {
            # 添加活跃人数
            $id = Db::table('chat_activity')->field('id')->where(array('chat_date' => date('Y-m-d'), 'chat_start' => $start, 'chat_end' => $hour))->find()['id'];
            if (!empty($id)) {
                # 增加人数
                Db::table('chat_activity')->where(array('id' => $id))->setInc('activity_num', 1);
            } else {
                # 添加数据
                Db::table('chat_activity')->insert(array(
                    'chat_date' => date('Y-m-d'),
                    'chat_start' => $start,
                    'chat_end' => $hour,
                    'activity_num' => 1
                ));
            }
            # 到下一个时间的过期时间
            $time = strtotime(date('Y-m-d ' . ($hour + 1) . ':00:00')) - time();
            $redis->hSet('chatActivity', $this->code . '=>' . $hour, 'YES', $time);
        }
        return array('status' => true);
    }

    /**
     * @return array
     * @throws \think\Exception
     * @content 查询历史聊天记录
     */
    function historyChatLog()
    {
        # 接收人
        $receiver = input('post.receiver');
        if (!empty($receiver)) {
            # 查询历史记录
            $info = Db::connect("db_config2")->table("chat")
                ->where(array("main" => $this->code, "relevance" => $receiver))->find();
            return array('status' => true, 'msg' => '查询成功', 'info' => $info);
        } else {
            # 查询所有聊天列表
            $info = Db::connect("db_config2")->table("chat")
                ->where(array("main" => $this->code))->order('time','desc')->select();
            return array('status' => true, 'msg' => '查询成功', 'info' => $info);
//            return array('status' => false, 'msg' => '请选择接收人');
        }
    }
    
    /**
     * @return array
     * @throws \think\Exception
     * @content 删除历史聊天记录
     */
    function delChatRecord()
    {
        # 接收人
        $receiver = input('post.receiver');
        if (!empty($receiver)) {
            # 查询历史记录
            Db::connect("db_config2")->table("chat")
                ->where(array("main" => $this->code, "relevance" => $receiver))->delete();
//            $info = Db::connect("db_config2")->table("chat")
//                ->where(array("main" => $this->code, "relevance" => $receiver))->find();
//            dump($info);
            return array('status' => true, 'msg' => '删除成功');
        } else {
            return array('status' => false, 'msg' => '请选择接收人');
        }
    }

    function demo()
    {
//        $redis = new Redis();
//        $redis->delete('recommendNum');
        Db::connect("db_config2")->table("chat")->where('id!=0')->delete();
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 投诉
     */
    function complaint()
    {
        # 接收被投诉人-ID
        $sell_code = input('post.sell_code');
        # 被投诉人信息
        $sellInfo = Db::table('member')->field('name,phone')->where(array('code' => strtoupper(trim($sell_code))))->find();
        # 接收投诉原因
        $reason = input('post.reason');
        # 接收投诉内容
        $complaint_context = input('post.complaint_context');
        # 接收投诉截图(英文逗号拼接字符串)
        $screenshot = json_decode(input("post.screenshot"), true);
        $_base_url = array();
        if (!empty($screenshot)) {
            foreach ($screenshot as $k => $v) {
                # 上传截图
                array_push($_base_url, ResourceService::uploadBase($v));
            }
        }
        $screenshot_info = implode(',', $_base_url);// 投诉图片逗号拼接
        # 添加投诉审核
        $res = Db::table("complaint")->insert(array("sell_code" => $this->code, "sell_name" => $this->memberInfo['name'], "sell_phone" => $this->memberInfo['phone'],
            "industry_id" => 0, "screenshot" => $screenshot_info, "buy_code" => $sell_code, "buy_name" => $sellInfo['name'],
            "buy_phone" => $sellInfo['phone'], "create_time" => date("Y-m-d H:i:s"), "reason" => $reason, "complaint_context" => $complaint_context,
            "trad_audit_id" => 0, 'type_mark' => 1));
        if ($res) {
            return array('status' => true, 'msg' => '提交审核成功');
        } else {
            return array('status' => false, 'msg' => '提交失败');
        }
    }
}
